//
//  HeadView.m
//  UITableView
//
//  Created by cocoazxj@163.com on 15/3/27.
//  Copyright (c) 2015年 handcool. All rights reserved.
//

#import "HeadView.h"

@interface HeadView()<UIScrollViewDelegate>
@property (nonatomic, strong) NSTimer *mTimer;
@end

@implementation HeadView
- (instancetype)initWithHeadView:(NSMutableArray *)array
{
    self = [[[NSBundle mainBundle] loadNibNamed:@"HeadView" owner:self options:nil] firstObject];
    self.sv_main.delegate = self;
    self.pc_num.numberOfPages = array.count;
    [self.sv_main setContentSize:CGSizeMake(array.count*250, 120)];
    self.sv_main.pagingEnabled = YES;
    for(int i = 0; i < array.count; i++)
    {
        UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(i*250, 0, 250, 120)];
        [iv setImage:[UIImage imageNamed:array[i]]];
        [self.sv_main addSubview:iv];
    }
    [self addNSTimer];
    return self;
}

- (void)addNSTimer
{
    self.mTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(nextPageNum) userInfo:nil repeats:YES];
    //    self.timer = [NSTimer timerWithTimeInterval:5.0 target:self selector:@selector(nextPageNum) userInfo:nil repeats:YES];
    //    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
}

- (void)removeNSTimer
{
    [self.mTimer invalidate];
    self.mTimer = nil;
}
- (void)nextPageNum
{
    NSInteger page;
    page = self.pc_num.currentPage;
    page ++;
    if (page == 5)
    {
        page = 0;
    }
    NSLog(@"----------%d",page);
    [self.sv_main setContentOffset:CGPointMake(250*page, 0) animated:YES];
}

// 滚动完成时，设置当前UIPageControl的页数，用于滚动时加1
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.pc_num.currentPage = (self.sv_main.contentOffset.x + 125)/250;
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self removeNSTimer];
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self addNSTimer];
}
@end
